﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using TransControlSystem.Dao;
using TransControlSystem.Model;
using TransControlSystem.Utils;
using TransControlSystem.ViewModel.Common;
using TransControlSystem.ViewModel.Common.Command;

namespace TransControlSystem.ViewModel
{
    /// <summary>
    /// 任务查询后台程序
    /// </summary>
    public class TaskQueryViewModel : ViewModelBase
    {
        /// <summary>
        /// 开始
        /// </summary>
        private int start = 0;
        /// <summary>
        /// 每页数量
        /// </summary>
        private int itemCount = 20;
        /// <summary>
        /// 摸摸人排序字段
        /// </summary>
        private string sortColumn = "StartTime";
        /// <summary>
        /// 正序还是反序
        /// </summary>
        private bool ascending = false;
        /// <summary>
        /// 总数量
        /// </summary>
        private int totalItems = 0;


        /// <summary>
        /// 开始
        /// </summary>
        public int Start { get { return start + 1; } }

        /// <summary>
        /// 最后一页
        /// </summary>
        public int End { get { return start + itemCount < totalItems ? start + itemCount : totalItems; } }

        /// <summary>
        /// 总数据量
        /// </summary>
        public int TotalItems { get { return totalItems; } }
        /// <summary>
        /// 首页命令
        /// </summary>
        public DelegateCommand FirstCommand { get; set; }
        /// <summary>
        /// 上一页命令
        /// </summary>
        public DelegateCommand PreviousCommand { get; set; }
        /// <summary>
        /// 下一页命令
        /// </summary>
        public DelegateCommand NextCommand { get; set; }
        /// <summary>
        /// 最后一页命令
        /// </summary>
        public DelegateCommand LastCommand { get; set; }

        /// <summary>
        /// 搜索命令
        /// </summary>
        public DelegateCommand SearchCommand { get; set; }

        /// <summary>
        /// 隐藏窗体命令
        /// </summary>
        public DelegateCommand HideTaskQueryWindowCommand { get; set; }

        /// <summary>
        /// UI任务列表
        /// </summary>
        private ObservableCollection<TaskInfo> _TaskInfos;
        /// <summary>
        /// UI任务列表
        /// </summary>
        public ObservableCollection<TaskInfo> TaskInfos
        {
            get { return _TaskInfos; }
            set
            {
                _TaskInfos = value;
                RaisePropertyChanged("TaskInfos");
            }
        }
        /// <summary>
        /// 搜索使用任务描述
        /// </summary>
        private string _TaskDesc;
        /// <summary>
        /// 搜索使用任务描述
        /// </summary>
        public string TaskDesc
        {
            get { return _TaskDesc; }
            set
            {
                _TaskDesc = value;
                RaisePropertyChanged("TaskDesc");
            }
        }

        /// <summary>
        /// 结束时间搜索使用的开始时间范围
        /// </summary>
        private string _StartTime;
        /// <summary>
        /// 结束时间搜索使用的开始时间范围
        /// </summary>
        public string StartTime
        {
            get { return _StartTime; }
            set
            {
                _StartTime = value;
                RaisePropertyChanged("StartTime");
            }
        }

        /// <summary>
        /// 结束时间搜索使用的结束时间范围
        /// </summary>
        private string _EndTime;
        /// <summary>
        /// 结束时间搜索使用的结束时间范围
        /// </summary>
        public string EndTime
        {
            get { return _EndTime; }
            set
            {
                _EndTime = value;
                RaisePropertyChanged("EndTime");
            }
        }

        /// <summary>
        /// 数据库中任务数量
        /// </summary>
        private ObservableCollection<TaskInfo> DataTaskInfos = new ObservableCollection<TaskInfo>();
        /// <summary>
        /// 构造函数
        /// </summary>
        public TaskQueryViewModel()
        {
            //获取所有任务列表平
            string WhereSql = " WHERE 1 = 1 AND Status = '已完成'";
            if (TaskDesc != null && TaskDesc.Trim() != "")
            {
                if (XyhUtils.IsHasSQLInject(TaskDesc))
                {
                    WindowManager.ShowWarning("警告", "任务描述不可使用包含SQL注入关键词的内容进行搜索操作！");
                    return;
                }
                WhereSql += " AND TaskDesc LIKE '%" + TaskDesc + "%'";
            }
            if (StartTime != null)
            {
                WhereSql += " AND EndTime >= CONVERT(datetime2(7),'" + StartTime + "')";
            }
            if (EndTime != null)
            {
                WhereSql += " AND EndTime <= CONVERT(datetime2(7),'" + EndTime + "')";
            }
            string Sql = "SELECT * FROM TaskInfo" + WhereSql + " ORDER BY StartTime ";
            List<TaskInfo> TagInfoList = DapperTools.Query<TaskInfo>(Sql);
            DataTaskInfos.Clear();
            TagInfoList.ForEach(obj =>
            {
                DataTaskInfos.Add(obj);
            });

            FirstCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(FirstFuncationHandler)
            };

            PreviousCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(PreviousFuncationHandler)
            };

            NextCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(NextFuncationHandler)
            };

            LastCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(LastFuncationHandler)
            };

            SearchCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(SearchHandler)
            };

            HideTaskQueryWindowCommand = new DelegateCommand()
            {
                ExecuteActionObj = new Action<object>(HideTaskQueryWindowHandler)
            };
            loadTaskInfos();
        }

        /// <summary>
        /// 搜索处理程序
        /// </summary>
        /// <param name="obj">参数</param>
        private void SearchHandler(object obj)
        {
            try
            {
                //获取所有任务列表平
                string WhereSql = " WHERE 1 = 1 AND Status = '已完成'";
                if (TaskDesc != null && TaskDesc.Trim() != "")
                {
                    if (XyhUtils.IsHasSQLInject(TaskDesc))
                    {
                        WindowManager.ShowWarning("警告", "任务描述不可使用包含SQL注入关键词的内容进行搜索操作！");
                        return;
                    }
                    WhereSql += " AND TaskDesc LIKE '%" + TaskDesc + "%'";
                }
                if (StartTime != null)
                {
                    WhereSql += " AND EndTime >= CONVERT(datetime2(7),'" + StartTime + "')";
                }
                if (EndTime != null)
                {
                    WhereSql += " AND EndTime <= CONVERT(datetime2(7),'" + EndTime + "')";
                }
                string Sql = "SELECT * FROM TaskInfo" + WhereSql;
                List<TaskInfo> TagInfoList = DapperTools.Query<TaskInfo>(Sql);
                DataTaskInfos.Clear();
                TagInfoList.ForEach(item =>
                {
                    DataTaskInfos.Add(item);
                });
                loadTaskInfos();
            }
            catch (Exception e)
            {
                LogTool.SaveSysLog(e.Message, "任务查询异常");
            }
        }
        /// <summary>
        /// 加载数据
        /// </summary>
        /// <param name="propertyName">Name of the changed property.</param>
        private void loadTaskInfos()
        {
            TaskInfos = GetTaskInfos(start, itemCount, sortColumn, ascending, out totalItems);
        }

        /// <summary>
        /// 隐藏任务查询窗体处理程序
        /// </summary>
        /// <param name="obj">参数</param>
        private void HideTaskQueryWindowHandler(object obj)
        {
            Messenger.Default.Send<NotificationMessage>(new NotificationMessage(this, "HideTaskQueryWindow"));
        }
        /// <summary>
        /// 首页处理程序
        /// </summary>
        /// <param name="obj">参数</param>
        private void FirstFuncationHandler(object obj)
        {
            if (Start - itemCount >= 0)
            {
                start = 0;
                RaisePropertyChanged("Start");
                RaisePropertyChanged("End");
                loadTaskInfos();
            }
        }
        /// <summary>
        /// 前一页处理程序
        /// </summary>
        /// <param name="obj">参数</param>
        private void PreviousFuncationHandler(object obj)
        {
            if (start - itemCount >= 0)
            {
                start -= itemCount;
                RaisePropertyChanged("Start");
                RaisePropertyChanged("End");
                loadTaskInfos();
            }
        }
        /// <summary>
        /// 下一页处理程序
        /// </summary>
        /// <param name="obj">参数</param>
        private void NextFuncationHandler(object obj)
        {
            if (start + itemCount < totalItems)
            {
                start += itemCount;
                RaisePropertyChanged("Start");
                RaisePropertyChanged("End");
                loadTaskInfos();
            }
        }
        /// <summary>
        /// 最后一页处理程序
        /// </summary>
        /// <param name="obj">参数</param>
        private void LastFuncationHandler(object obj)
        {
            if (start + itemCount < totalItems)
            {
                start = (totalItems / itemCount - 1) * itemCount;
                start += totalItems % itemCount == 0 ? 0 : itemCount;
                RaisePropertyChanged("Start");
                RaisePropertyChanged("End");
                loadTaskInfos();
            }
        }

        /// <summary>
        ///  获取分页数据
        /// </summary>
        /// <param name="start">从零开始的索引，用于确定展示的列表的起始。</param>
        /// <param name="itemCount">每页显示数量</param>
        /// <param name="sortColumn">排序字段</param>
        /// <param name="ascending">排序方式</param>
        /// <param name="totalItems">总数量</param>
        /// <returns>结果列表</returns>
        public ObservableCollection<TaskInfo> GetTaskInfos(int start, int itemCount, string sortColumn, bool ascending, out int totalItems)
        {
            totalItems = DataTaskInfos.Count;
            ObservableCollection<TaskInfo> sortedTaskInfos = new ObservableCollection<TaskInfo>();
            switch (sortColumn)
            {
                case "Id":
                    sortedTaskInfos = new ObservableCollection<TaskInfo>
                    (
                        from p in DataTaskInfos
                        orderby p.Id
                        select p
                    );
                    break;
                case "CreateTime":
                    sortedTaskInfos = new ObservableCollection<TaskInfo>
                    (
                        from p in DataTaskInfos
                        orderby p.CreateTime
                        select p
                    );
                    break;
                case "StartTime":
                    sortedTaskInfos = new ObservableCollection<TaskInfo>
                    (
                        from p in DataTaskInfos
                        orderby p.StartTime
                        select p
                    );
                    break;
                case "EndTime":
                    sortedTaskInfos = new ObservableCollection<TaskInfo>
                    (
                        from p in DataTaskInfos
                        orderby p.EndTime
                        select p
                    );
                    break;
            }
            sortedTaskInfos = ascending ? sortedTaskInfos : new ObservableCollection<TaskInfo>(sortedTaskInfos.Reverse());
            ObservableCollection<TaskInfo> filteredTaskInfos = new ObservableCollection<TaskInfo>();
            for (int i = start; i < start + itemCount && i < totalItems; i++)
            {
                sortedTaskInfos[i].DataOrderNo = i + 1;
                filteredTaskInfos.Add(sortedTaskInfos[i]);
            }
            return filteredTaskInfos;
        }
    }
}
